package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;


@Component
public class ManagerFilter extends ZuulFilter {


    @Autowired
    private JwtUtil jwtUtil;



    /**
     * 在请求前pre或 后 post执行
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器 执行顺序，数值越小，越先执行
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启过滤器
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器执行操作 return 任何object的值都表示继续执行
     * setsendzullResponse(false)表示不再继续执行
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("经过后台过滤器了");
        //得到request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        if(request.getRequestURI().indexOf("login")>0){
            return  null;
        }

        //得到头信息
        String header = request.getHeader("Authorization");

        if(header!=null && !"".equals(header)){
            if(header.startsWith("Bearer ")){
                String token = header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    if(roles.equals("admin")){
                        //转发头信息
                        requestContext.addZuulRequestHeader("Authorization",header);
                        //放行
                        return null;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    requestContext.setSendZuulResponse(false);  //终止运行
                }
            }

        }

        requestContext.setSendZuulResponse(false);  //终止运行
        requestContext.setResponseStatusCode(403);
        requestContext.setResponseBody("权限不足");
        requestContext.getResponse().setContentType("text/html;charset=utf-8");

        return null;
    }
}
